#include "util.h"

#include <QApplication>
#include <QLabel>
#include <QTimer>
#include <QPropertyAnimation>
#include <QScreen>

//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void ShowToast(const QString& message, QWidget *parent) {
    QLabel *toast = new QLabel(parent);
    toast->setText(message);
    toast->setStyleSheet("QLabel { background-color: rgba(0, 180, 0, 180); "
                         "color: white; padding: 10px; border-radius: 8px; }");
    toast->setWindowFlags(Qt::FramelessWindowHint | Qt::Tool | Qt::WindowStaysOnTopHint);
    toast->setAttribute(Qt::WA_TranslucentBackground); // 关键：允许窗口透明
    toast->adjustSize();

	if (parent) {
		QPoint parentCenter = parent->geometry().center();
		// 注意：geometry() 是相对于父窗口的父窗口（通常是屏幕），但 move() 需要的是父窗口坐标系
		// 所以要用 mapToGlobal
		QPoint globalCenter = parent->mapToGlobal(parent->rect().center());
		toast->move(globalCenter.x() - toast->width()/2,
					globalCenter.y() - toast->height()/2);
	} else {
		// 没有父窗口时，退回到屏幕中心
		QPoint centerPos = QApplication::primaryScreen()->geometry().center();
		toast->move(centerPos.x() - toast->width()/2, 
					centerPos.y() - toast->height()/2);
	}
    toast->show();

    // 淡出动画
    QTimer::singleShot(2000, [toast]() {
        QPropertyAnimation *anim = 
            new QPropertyAnimation(toast, "windowOpacity");
        anim->setDuration(1000);
        anim->setStartValue(1.0);
        anim->setEndValue(0.0);
        QObject::connect(anim, &QPropertyAnimation::finished, toast, 
            &QLabel::deleteLater);
        anim->start(QAbstractAnimation::DeleteWhenStopped);
    });
}
